package com.xxhui.fragmentdemo.Framment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.xxhui.fragmentdemo.R;

/**
 * Created by Administrator on 2016/8/7.
 */
public class FragmentA extends Fragment implements View.OnClickListener {

    private FragmentAListener listener;
    private Button button;

    /**
     * 此方法与activity中的onCreate方法一样，在生命周期只执行一次
     * 所以此方法适合初始化资源
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);//通知activity，fragment需要使用菜单
        listener = (FragmentAListener) getActivity();
    }

    /**
     * @param container container 参数是您的Fragment布局将插入到的父 ViewGroup（来自 Activity 的布局）
     * @return 返回的一定要是根视图，不提供ui则可直接返回null
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_a_layout, container, false);
        button = (Button) v.findViewById(R.id.send_msg_to_activity_but);
        button.setOnClickListener(this);
        registerForContextMenu(v);//注册上下文菜单
        return v;
    }

    @Override
    public void onPause() {
        super.onPause();
    }


    public interface FragmentAListener {
        void sendMsg(String msg);
    }

    @Override
    public void onClick(View view) {
        listener.sendMsg("i am fragmentA");
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.add(0,1,2,"FragmentMenu");
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case 1:
                button.setBackgroundColor(Color.GREEN);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0,1,2,"fragmentContentMenu");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case 1:
                button.setBackgroundColor(Color.CYAN);
                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }
}
